package com.cmpe.group6.storyroad;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.cmpe.group6.storyroad.ListAdapters.FollowingAdapter;
import com.cmpe.group6.storyroad.jsonClasses.FollowObject;
import com.cmpe.group6.storyroad.jsonClasses.FollowObjectHolder;
import com.google.gson.Gson;

/** Activity for following other users.
 * @author alicang
 *
 */
public class FollowingActivity extends Activity {

	private FollowObject[] followedUsers;
	private ArrayList<String> usernames = new ArrayList<String>();
	private ArrayList<String> followers = new ArrayList<String>();
	private ArrayList<Bitmap> profilePictures = new ArrayList<Bitmap>();
	private ProgressBar progressBar;
	private FollowTask fTask;
	private ListView followingList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_following);
		followingList = (ListView) findViewById(R.id.following_list);
		progressBar = (ProgressBar) findViewById(R.id.progressBar_follow);

		fTask = new FollowTask();
		fTask.execute((Void) null);

		// Clicking an item on following list directs the user to clicked user's
		// profile page.
		followingList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						String username = (String) followingList
								.getItemAtPosition(position);
						Intent profileIntent = new Intent(
								getApplicationContext(), ProfileActivity.class);
						profileIntent.putExtra("targetname", username);
						startActivity(profileIntent);
					}
				});
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/*	Activating the top bar.
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.home_button:
			Intent mainIntent = new Intent(this, MainActivity.class);
			startActivity(mainIntent);
			return true;
		case R.id.recommendations_button:
			Intent recomIntent = new Intent(this, RecommendationsActivity.class);
			startActivity(recomIntent);
			return true;
		case R.id.profile_button:
			Intent profileIntent = new Intent(this, ProfileActivity.class);
			startActivity(profileIntent);
			return true;
		case R.id.search_button:
			Intent searchIntent = new Intent(this, SearchActivity.class);
			startActivity(searchIntent);
			return true;
		case R.id.following_button:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Represents an asynchronous Follow task for getting the users followed by
	 * the active user.
	 * 
	 */
	public class FollowTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			progressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME + "GetFollowers");

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs.add(new BasicNameValuePair("username",
						Utils.username));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				followedUsers = gson.fromJson(jsonResponse,
						FollowObjectHolder.class).getFollowedPeople();

				for (FollowObject followObject : followedUsers) {
					URL newurl;
					Bitmap pic = null;
					try {
						newurl = new URL(followObject.getPhotoLink());
						pic = BitmapFactory.decodeStream(newurl
								.openConnection().getInputStream());
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					profilePictures.add(pic);
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			return true;
		}
		
		/*
		 * (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(getApplicationContext(), "Connection Error",
						Toast.LENGTH_SHORT).show();
			} else {
				for (int i = 0; i < followedUsers.length; i++) {
					usernames.add(followedUsers[i].getUsername());
					followers.add(String.valueOf(followedUsers[i]
							.getFollowerCount()));
				}
				FollowingAdapter adapter = new FollowingAdapter(
						getApplicationContext(), usernames, followers,
						profilePictures);
				followingList.setAdapter(adapter);
				progressBar.setVisibility(View.GONE);
			}
		}

		@Override
		protected void onCancelled() {

		}
	}

}
